package com.platform.service.impl;

import com.platform.annotation.SysLog;
import com.platform.base.BaseService;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.dao.LogMapper;
import com.platform.service.ISendMessageSeivice;
import com.platform.util.PostInterfaceApi;
import com.platform.util.PropertiesUtil;
import com.platform.util.StringUtil;
import com.platform.util.ToolUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 发送消息类
 */
@Service("iSendMessageSeivice")
public class SendMessageServiceImpl extends BaseService implements ISendMessageSeivice {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(SendMessageServiceImpl.class);

    /**
     * 发送短信验证码
     * @param request
     * @return
     */
    @Override
    @SysLog("发送手机验证码")
    public ServerResponse sendMessage(Map param, HttpServletRequest request) {
        //验证IP,请求方法名,以及时间，防止恶意调用短信接口
        int maxNums = Const.RequestNums.MAXREQUESTMESSAGE;//请求最大数
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
        String dateStr = sdf.format(new Date());
        int nums = logMapper.countNumByParam(ToolUtil.getClientIp(request),request.getRequestURI(),dateStr);
        if(nums >= maxNums){
            return ServerResponse.createByErrorMessage("当日请求次数过多");
        }
        //获取配置参数
        String httpurl = PropertiesUtil.getProperty("message.httpurl");
        String userid = PropertiesUtil.getProperty("message.userid");
        String username = PropertiesUtil.getProperty("message.username");
        String password = PropertiesUtil.getProperty("message.password");
        //随机生成6位数字
        int randomNum = (int)((Math.random()*9+1)*100000);
        logger.info("短信验证码："+randomNum);
        //存入session
        request.getSession().setAttribute(Const.CodeType.PHONECODE,randomNum);
        PostInterfaceApi.httpURLConnectionPOST(httpurl,
                "您的验证码为:"+randomNum,
                StringUtil.valueOfString(param.get("phoneNumber")),userid,
                username,password);
        return ServerResponse.createBySuccessMessage("发送成功");
    }
}
